package 剑指Offer;

public class Offer52_两个链表的第一个公共节点 {


    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int aLength = length(headA);
        int bLength = length(headB);

        while (aLength != bLength) {//让长度长的先走，直到二者长度相同，再同时前进
            if (aLength > bLength) {
                headA = headA.next;
                aLength--;
            } else {
                headB = headB.next;
                bLength--;
            }
        }

        //同时前进
        while (headA != headB) {
            headA = headA.next;
            headB = headB.next;
        }
        //head要么为null，要么就是相遇的第一个节点
        return headA;
    }


    //统计链表的长度
    private int length(ListNode node) {
        int length = 0;
        while (node != null) {
            node = node.next;
            length++;
        }
        return length;
    }
}
